package com.rzgeo.wcgallay.model;

import android.content.Intent;
import android.graphics.Bitmap;
import android.media.MediaActionSound;
import android.net.Uri;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;

import com.esri.arcgisruntime.concurrent.ListenableFuture;
import com.esri.arcgisruntime.mapping.view.GeoView;
import com.rzgeo.rzmaplib.util.RmlUtil;
import com.rzgeo.wcgallay.util.WcmEnv;
import com.rzgeo.wcgallay.util.WcmUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Created by zhanghang on 2018/1/11.
 */

public class WcmMapTool {


    private final GeoView geoView;
    private final AppCompatActivity activity;

    public WcmMapTool(GeoView geoView, AppCompatActivity activity){
        this.geoView =geoView;
        this.activity=activity;
    }
    public void screenShot(final RmlUtil.Dialog.OnResult onFinish){
        final ListenableFuture<Bitmap> export = geoView.exportImageAsync();
        export.addDoneListener(new Runnable() {
            @Override
            public void run() {
                try {
                    Bitmap currentMapImage = export.get();
                    // play the camera shutter sound
                    MediaActionSound sound = new MediaActionSound();
                    sound.play(MediaActionSound.SHUTTER_CLICK);
                    WcmUtil.Tip.Toast("保存地图截屏");
                    SaveImageTask saveImageTask = new SaveImageTask();
                    saveImageTask.execute(currentMapImage);
                    if(onFinish!=null)
                        onFinish.OnResult(true);
                } catch (Exception e) {
                    WcmUtil.Tip.Toast("保存地图截屏失败");
                    if(onFinish!=null)
                        onFinish.OnResult(false);
                }
            }
        });

    }


    /**
     * AsyncTask class to save the bitmap as an image
     */
    private class SaveImageTask extends AsyncTask<Bitmap, Void, File> {

        private boolean _share;

        protected void onPreExecute() {
            // display a toast message to inform saving the map as an image
        }

        /**
         * save the file using a worker thread
         */
        protected File doInBackground(Bitmap... mapBitmap) {

            try {
                return saveToFile(mapBitmap[0]);
            } catch (Exception e) {
                WcmUtil.Tip.Alert("保存失败：" + e.getMessage());
            }

            return null;

        }

        /**
         * Perform the work on UI thread to open the exported map image
         */
        protected void onPostExecute(File file) {

            if(_share){

                // Open the file to view
                Intent i = new Intent();
                i.setAction(android.content.Intent.ACTION_VIEW);
                i.setDataAndType(Uri.fromFile(file), "image/png");
                activity.startActivity(i);
            }else{

            }
        }

        /**
         * save the bitmap image to file and open it
         *
         * @param bitmap
         * @throws IOException
         */
        private File saveToFile(Bitmap bitmap) throws IOException {

            // create a directory ArcGIS to save the file
            File root;
            File file = null;
            String fileName = "map-export-image" + System.currentTimeMillis() + ".png";

            File fileDir = WcmEnv.getDefaultInst().getAppStandFolder().screenShotFolder;
//            File fileDir = new File(root.getAbsolutePath() + "/ArcGIS Export/");

            boolean isDirectoryCreated=fileDir.exists();
            if (!isDirectoryCreated) {
                isDirectoryCreated= fileDir.mkdirs();
            }
            if(isDirectoryCreated) {
                file = new File(fileDir, fileName);
                // write the bitmap to PNG file
                FileOutputStream fos = new FileOutputStream(file);
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);

                // close the stream
                fos.flush();
                fos.close();
            }
            return file;

        }
    }

}
